<template>
  <div class="col-xs-12 col-md-8 offset-md-2">
    <!-- 发布评论的表单 -->
    <form class="card comment-form">
      <div class="card-block">
        <textarea class="form-control" placeholder="Write a comment..." rows="3" v-model="comment.body"></textarea>
      </div>
      <div class="card-footer">
        <img src="http://i.imgur.com/Qr71crq.jpg" class="comment-author-img" />
        <button class="btn btn-sm btn-primary" :disabled='submitDisabled' @click="submitComment"> Post Comment </button>
      </div>
    </form>
    <!-- 评论列表内容 -->
    <div class="card" v-for="(item, index) in comments" :key="index">
      <div class="card-block">
        <p class="card-text" v-html="item.body"></p>
      </div>
      <div class="card-footer">
        <nuxt-link class="nav-link comment-author" :to="{name: 'profile', params: {username: item.author.username}}">
           <img :src="item.author.image" class="comment-author-img"/>&nbsp;
           <span class="comment-author">{{item.author.username}}</span>
        </nuxt-link> &nbsp;
        <span class="date-posted">{{item.updatedAt | date('MMM DD, YYYY')}}</span>
        <span class="mod-options" v-if="item.author.username == user.username">
          <i class="ion-trash-a" @click="handleDeleteComment(item.id)"></i>
        </span>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import MarkdownIt from 'markdown-it'
import { addComment, deleteComment, getComments } from '@/api/article'
export default {
  props:{
    article:{
      typeof: Object,
      require: true
    }
  },
  computed: {
    ...mapState('user', { user: 'user'})
  },
  data(){
    return {
      comments:[], // 评论列表内容
      comment:{
        body: '' // 添加评论的正文内容
      },
      submitDisabled:  false, // 添加评论按钮是否禁用
      deleteCommentDisbaled: false, //删除评论的按钮是否禁用
    }
  },
  created(){
    this.loadComments()
  },
  methods:{
    // 获取文章评论数据
    loadComments(){
      getComments(this.article.slug).then(res=>{
        res.comments.forEach(e => {
          // 解析文章正文内容的markDowm语法
          const md = new MarkdownIt()
          e.body = md.render(e.body)
        });
        this.comments = res.comments
      }).finally(()=>{

      })
    },
    // 发布评论
    submitComment(){
      this.submitDisabled = true
      addComment(this.article.slug, {...this.comment}).then(()=>{
        //更新评论列表
        this.loadComments()
      }).finally(()=>{
        this.submitDisabled = false
      })
    },
    //删除文章评论
    handleDeleteComment(id){
      if(this.deleteCommentDisbaled) return
      this.deleteCommentDisbaled = true
      deleteComment(this.article.slug, id).then(()=>{
        //更新评论列表
        this.loadComments()
      }).finally(()=>{
        this.deleteCommentDisbaled = false
      })
    }
  }
}
</script> 